package com.scut.shangxueguan.interceptors;

import com.scut.shangxueguan.constant.AdministratorConstant;
import com.scut.shangxueguan.utils.JwtUtil;
import com.scut.shangxueguan.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class LoginInterceptor implements HandlerInterceptor {

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(token == null || token.isEmpty()) {
            // System.out.println("token is null, 拦截");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            String redisToken = stringRedisTemplate.opsForValue().get(AdministratorConstant.LOGIN_KEY
                    + claims.get("id").toString());
            // token没过期时，判断两次密码是否相等
            if(redisToken == null || !redisToken.equals(token)) {
                // System.out.println("token 不一致");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return false;
            }
            ThreadLocalUtil.set(claims);
            return true;
        } catch (RuntimeException e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
